#!/usr/bin/python3

import requests
import json
import openai
import secrets_info

api_key = secrets_info.GPT4_API_KEY
api_base = secrets_info.GPT4_URL_BASE
model="gpt-3.5-turbo-0613"

def get_weather(locale):
    openweather_key="9c8051bdbcec4574fa6c00cf831b5d87"
    openweather_url="https://api.openweathermap.org/data/2.5/weather"

    weather_params = {
        "q": locale,
        "appid": openweather_key,
        "units": "metric",
        "lang": "zh_cn"
    }
    print("query city: ", locale)
    weather_response = requests.get(openweather_url, params=weather_params)
    data = weather_response.json()
    return json.dumps(data)

get_weather_function = {
    'name': 'get_weather',
    'description': '查询当前天气函数,根据输入的城市名称,查询对应城市的实时天气',
    'parameters': {
        'type': 'object',
        'properties': {
            'locale': {
                'description': '城市名称,注意,中国的城市需要用对应城市的英文名称代替,例如查询北京市的天气,locale参数需要输入Beijing',
                'type': 'string'
            }
        },
        'requires': ['locale']
    }
}

available_functions = {
    "get_weather": get_weather
}

openai.api_key = api_key
openai.api_base = api_base

def chatgpt(prompt):
    messages = [
        {"role": "user", "content": prompt}
    ]

    # 调用OpenAI ChatCompletion.create函数进行对话生成
    response = openai.ChatCompletion.create(
        model = model,
        functions = [get_weather_function],
        function_call = "auto",
        messages = messages
    )

    response_messages = response['choices'][0]['message']
    print('receive response_messages')

    if "function_call" in response_messages:
        function_name = response_messages['function_call']['name']
        function_args = json.loads(response_messages['function_call']['arguments'])
        
        print('calling function [%s]' % function_name)
        function_response = available_functions[function_name](**function_args)
        print('receive function_response')

        messages.append(response_messages)
        messages.append({
            "role": "function",
            "name": function_name,
            "content": function_response
        })

        second_response = openai.ChatCompletion.create(
            model = model,
            messages = messages
        )

        second_response_messages = second_response['choices'][0]['message']
        print('receive second_response_messages')
    return second_response_messages['content']

print(chatgpt("请帮我查询天津的天气"))

